/**********************************************************************
  * @file:        xxx.c
  * @author:      guangjieMVP
  * @version:     v1.00.00
  * @date:        2020-xx-xx
  * @github:      https://github.com/guangjieMVP
  * @brief: 
************************************************************************/
#include <pthread.h>
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <fcntl.h>
#include <stdlib.h>

int global = 0;  

pthread_mutex_t mtu_lock = PTHREAD_MUTEX_INITIALIZER; //定义互斥锁并初始化
pthread_cond_t  cond = PTHREAD_COND_INITIALIZER;  //定义条件变量并初始化

void *thread1_entery (void *arg)
{   
    while (1)
    {
        pthread_mutex_lock(&mtu_lock);
        global++;
        printf("thread1 global : %d\r\n", global);
        pthread_cond_signal(&cond); //通知唤醒等待条件变量的线程 
        if (global >= 10)
        {
            pthread_mutex_unlock(&mtu_lock); //解锁
            pthread_exit(NULL); //退出线程
        }
        pthread_mutex_unlock(&mtu_lock);
        sleep(1);
    }
    printf("thread1 exit\r\n");
    
}

void *thread2_entery (void *arg)
{
    while (1)
    {
        pthread_mutex_lock(&mtu_lock);
        while (global < 10)
        {
            pthread_cond_wait(&cond, &mtu_lock);  //通知唤醒等待条件变量的线程
        }
        printf("thread2 global : %d\r\n", global);
        pthread_mutex_unlock(&mtu_lock);   
        pthread_exit(NULL);    
    }
    printf("thread2 exit\r\n");
     
}

int main(int argc, char **argv)
{
    pthread_t thread1;
    pthread_t thread2;

    int retval;

    retval =  pthread_create(&thread1, NULL, thread1_entery, NULL);
    if (retval < 0)
        exit(0);
    retval =  pthread_create(&thread2, NULL, thread2_entery, NULL);
    if (retval < 0)
    {
        pthread_cancel(thread1);
        exit(0);
    }
        
    pthread_join(thread1, NULL); //等待线程退出
    pthread_join(thread2, NULL);

    pthread_mutex_destroy(&mtu_lock); //销毁互斥锁
    pthread_cond_destroy(&cond); //销毁条件变量

    printf("end\r\n");

    return 0;
}